package com.huatao.subject.common.utils;

import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class RedisIdWorker {

    @Resource
    private RedisTemplate redisTemplate;

    private static final long BEGIN_TIMESTAMP = 1640995200L;

    private static final int COUNTBIT = 32;

    public long nextId(String keyPreFix) {
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long count = redisTemplate.opsForValue().increment("icr:" + keyPreFix + ":" + date);
        return timestamp << COUNTBIT | count;
    }

}
